﻿using System;
using System.IO;
using System.Linq;
using System.Threading;

namespace Kotonoha.Client.Synch {

    public class SynchronizationManager {
        public static event Action SynchStart;
        public static event Action SynchEnd;
        private static SynchronizationManager instance;

        private DirectoryInfo dir;

        private bool inSynch;

        private SynchronizationManager() {}

        public static void Start(string dir) {
            if (instance == null) {
                SynchronizationManager manager = new SynchronizationManager();
                manager.dir = new DirectoryInfo(dir);
                Thread t = new Thread(manager.watch);
                t.Name = "Synchronization watcher thread";
                t.IsBackground = true;
                t.Start();
                instance = manager;
            }
        }

        private void watch() {
            while (true) {
                FileInfo[] begin = dir.GetFiles("synch_token_begin");
                if (begin.Length != 0 && !inSynch) {
                    if (SynchStart != null) {
                        SynchStart.Invoke();
                    }
                    inSynch = true;
                    return;
                }

                FileInfo[] end = dir.GetFiles("synch_token_end");
                if (end.Length != 0) {
                    if (SynchEnd != null) {
                        SynchEnd.Invoke();
                    }
                    foreach (var info in end) {
                        info.Delete();
                    }
                    inSynch = false;
                }

                Thread.Sleep(250);
            }
        }
    }
}
